const express = require('express')
const { ApolloServer, gql } = require('apollo-server-express')

const typeDefs = gql`
  type Student {
    sname: String
    age: Int
    favour: String
  }
  type Query {
    hello: String
    stu: Student
  }
`

const resolvers = {
  Student: {
    sname: parent => {
      // 对子节点来说,parent起作用
      console.log(parent, '1')
      return '张三'
    },
    favour: parent => {
      if (parent.favour === 'swimming') {
        return '游泳'
      } else {
        return parent.favour
      }
    }
  },

  Query: {
    hello: () => 'Hello world!111',
    stu: parent => {
      console.log(parent, '2') // 对根节点来说,parent不起作用
      return {
        sname: '李四',
        age: 12,
        favour: 'swimming'
      }
    }
  }
}

const server = new ApolloServer({ typeDefs, resolvers })

const app = express()
server.applyMiddleware({ app })

app.listen({ port: 4000 }, () => console.log('Now browse to http://localhost:4000' + server.graphqlPath))
